package com.conduit.WinReg;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.exceptions.RegistryException;

public class WindowsReqistry {

	static final public String registryFormat = ".*(%s)\\s*(\\w*)\\s*(.*)";
	static final public String registryErrorFormat = ".*ERROR:\\s*(.*)";

	public static final String readRegistry(String location, String key) throws Exception {

		Process process = Runtime.getRuntime().exec("reg query " + '"' + location + "\" /v " + key);

		StreamReader reader = new StreamReader(process.getInputStream());
		reader.start();
		process.waitFor();
		reader.join();
		String output = reader.getResult();
		// validate the output
		// TODO add exception if value was not found
		if (output.matches(registryFormat)) {
			Matcher matcher = Pattern.compile(registryErrorFormat).matcher(output);
			if (matcher.find()) {
				RegistryException e = new RegistryException();
				e.setMessage(matcher.group(1));
				throw e;

			}
		}
		// get the value
		Matcher matcher = Pattern.compile(String.format(registryFormat, key.replace("\"", ""))).matcher(output);

		if (matcher.find()) {
			return matcher.group(3);
		} else {
			RegistryException e = new RegistryException();
			e.setMessage("Registry Query Result is Unavailable, Please Check Your Query");
			throw e;
		}

	}

	static class StreamReader extends Thread {
		private InputStream is;
		private StringWriter sw = new StringWriter();

		public StreamReader(InputStream is) {
			this.is = is;
		}

		public void run() {
			try {
				int c;
				while ((c = is.read()) != -1)
					sw.write(c);
			} catch (IOException e) {
			}
		}

		public String getResult() {
			return sw.toString();
		}
	}
}